<?php
$page_title = '在职员工管理 - 考务管理系统';

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    header('Location: index.php');
    exit();
}

// 数据库连接
try {
    require_once 'database.php';
    $db_connected = isset($conn) && $conn instanceof mysqli;
} catch (Exception $e) {
    error_log("数据库连接失败: " . $e->getMessage());
    $db_connected = false;
}

if (!$db_connected) {
    $_SESSION['error_message'] = "数据库连接失败，请联系管理员";
    header('Location: user_home.php');
    exit();
}

// 处理退休操作
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['retire'])) {
    if (!empty($_POST['user_ids'])) {
        $conn->begin_transaction();
        try {
            $user_ids = $_POST['user_ids'];
            $placeholders = implode(',', array_fill(0, count($user_ids), '?'));
            $types = str_repeat('s', count($user_ids));

            // 更新员工状态为退休
            $sql = "UPDATE staff SET serving = FALSE WHERE user_id IN ($placeholders)";
            $stmt_update = $conn->prepare($sql);
            $stmt_update->bind_param($types, ...$user_ids);
            $stmt_update->execute();

            $conn->commit();
            $success_message = "成功将 " . count($user_ids) . " 名员工标记为退休状态";
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "操作失败: " . $e->getMessage();
        }
    } else {
        $error_message = "请至少选择一名员工";
    }
}

// 处理更新风险指数请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_risk_indexes'])) {
    header('Content-Type: application/json');
    
    try {
        $conn->begin_transaction();
        
        // 获取所有在职员工
        $staff_query = "SELECT user_id FROM staff WHERE serving = TRUE";
        $staff_result = $conn->query($staff_query);
        
        if (!$staff_result) {
            throw new Exception("查询在职员工失败");
        }
        
        $updated_count = 0;
        
        while ($staff_row = $staff_result->fetch_assoc()) {
            $user_id = $staff_row['user_id'];
            
            // 计算该员工的总风险指数（所有违反纪律积分之和）
            $violations_query = "SELECT SUM(disciplinary_violation_points) as total_points FROM violations WHERE invigilator_id = ?";
            $stmt = $conn->prepare($violations_query);
            $stmt->bind_param('s', $user_id);
            $stmt->execute();
            $violations_result = $stmt->get_result();
            $violations_row = $violations_result->fetch_assoc();
            
            $total_risk_index = $violations_row['total_points'] ?? 0;
            
            // 更新员工的风险指数
            $update_query = "UPDATE staff SET risk_index = ? WHERE user_id = ?";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bind_param('ds', $total_risk_index, $user_id);
            
            if ($update_stmt->execute()) {
                $updated_count++;
            }
        }
        
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => "成功更新了 {$updated_count} 名在职员工的风险指数"
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
    
    exit();
}

// 构建部门ID与名称的映射关系
$UserTreeURLList = [
    ['校区清单', '/inc/user_list/tree.php?DEPT_ID=0'],
    ['丝织路主校区-校长室', '/inc/user_list/tree.php?DEPT_ID=1'],
    ['丝织路主校区-办公室', '/inc/user_list/tree.php?DEPT_ID=2'],
    ['丝织路主校区-教务室', '/inc/user_list/tree.php?DEPT_ID=3'],
    ['丝织路主校区-学生发展室', '/inc/user_list/tree.php?DEPT_ID=4'],
    ['丝织路主校区-总务处', '/inc/user_list/tree.php?DEPT_ID=5'],
    ['丝织路主校区-实训与培训处', '/inc/user_list/tree.php?DEPT_ID=6'],
    ['丝织路主校区-信息中心', '/inc/user_list/tree.php?DEPT_ID=7'],
    ['丝织路主校区-信息技术系', '/inc/user_list/tree.php?DEPT_ID=8'],
    ['丝织路主校区-智能制造系', '/inc/user_list/tree.php?DEPT_ID=9'],
    ['丝织路主校区-汽车技术系', '/inc/user_list/tree.php?DEPT_ID=10'],
    ['人民路教学点', '/inc/user_list/tree.php?DEPT_ID=11'],
    ['绿岛湖实训基地-艺术专业部', '/inc/user_list/tree.php?DEPT_ID=12'],
    ['丝织路主校区-校工会', '/inc/user_list/tree.php?DEPT_ID=14'],
    ['绿岛湖实训基地-办公室', '/inc/user_list/tree.php?DEPT_ID=34'],
    ['绿岛湖实训基地-教务处', '/inc/user_list/tree.php?DEPT_ID=35'],
    ['绿岛湖实训基地-学生处', '/inc/user_list/tree.php?DEPT_ID=36'],
    ['绿岛湖实训基地-总务处', '/inc/user_list/tree.php?DEPT_ID=37'],
    ['南庄教学点-办公室', '/inc/user_list/tree.php?DEPT_ID=38'],
    ['南庄教学点-教务处', '/inc/user_list/tree.php?DEPT_ID=39'],
    ['南庄教学点-学生处', '/inc/user_list/tree.php?DEPT_ID=40'],
    ['南庄教学点-总务处', '/inc/user_list/tree.php?DEPT_ID=41'],
    ['丝织路主校区-财务室', '/inc/user_list/tree.php?DEPT_ID=42'],
    ['南庄教学点-基础科组', '/inc/user_list/tree.php?DEPT_ID=44'],
    ['南庄教学点-机械科组', '/inc/user_list/tree.php?DEPT_ID=45'],
    ['丝织路主校区-示范办', '/inc/user_list/tree.php?DEPT_ID=46'],
    ['南庄教学点-校长室', '/inc/user_list/tree.php?DEPT_ID=48'],
    ['丝织路主校区-实训与培训室场室管理员', '/inc/user_list/tree.php?DEPT_ID=49'],
    ['丝织路主校区-外聘教师', '/inc/user_list/tree.php?DEPT_ID=51'],
    ['丝织路主校区-学校发展室', '/inc/user_list/tree.php?DEPT_ID=52'],
    ['丝织路主校区-顾问室', '/inc/user_list/tree.php?DEPT_ID=53'],
    ['丝织路主校区-绿岛湖校区校本部上课教师', '/inc/user_list/tree.php?DEPT_ID=54'],
    ['江湾教学点-校长室', '/inc/user_list/tree.php?DEPT_ID=56'],
    ['江湾教学点-办公室', '/inc/user_list/tree.php?DEPT_ID=57'],
    ['江湾教学点-教务处', '/inc/user_list/tree.php?DEPT_ID=58'],
    ['江湾教学点-学生处', '/inc/user_list/tree.php?DEPT_ID=59'],
    ['江湾教学点-实训与培训处', '/inc/user_list/tree.php?DEPT_ID=60'],
    ['江湾教学点-总务处', '/inc/user_list/tree.php?DEPT_ID=61'],
    ['江湾教学点-语数英科组', '/inc/user_list/tree.php?DEPT_ID=62'],
    ['江湾教学点-公共基础课科组', '/inc/user_list/tree.php?DEPT_ID=65'],
    ['江湾教学点-会计科组', '/inc/user_list/tree.php?DEPT_ID=68'],
    ['江湾教学点-电子商务科组', '/inc/user_list/tree.php?DEPT_ID=69'],
    ['南庄教学点-工美科组', '/inc/user_list/tree.php?DEPT_ID=74'],
    ['丝织路主校区-党委', '/inc/user_list/tree.php?DEPT_ID=73'],
    ['丝织路主校区-双高办', '/inc/user_list/tree.php?DEPT_ID=75'],
    ['丝织路主校区-体育科组', '/inc/user_list/tree.php?DEPT_ID=76'],
    ['绿岛湖实训基地-园林科组', '/inc/user_list/tree.php?DEPT_ID=77'],
    ['绿岛湖实训基地-公共基础科组', '/inc/user_list/tree.php?DEPT_ID=78'],
    ['技工学校', '/inc/user_list/tree.php?DEPT_ID=82']
];

$deptMap = [];
foreach ($UserTreeURLList as $item) {
    $url = $item[1];
    $query = parse_url($url, PHP_URL_QUERY);
    parse_str($query, $params);
    if (isset($params['DEPT_ID'])) {
        $dept_id = (int)$params['DEPT_ID'];
        $deptMap[$dept_id] = $item[0];
    }
}

// 查询在职员工数据（serving=true）
$sql = "SELECT user_id, name, online_status, dept_id, position, gender, latest_login, service_years, risk_index, created_at, updated_at
        FROM staff
        WHERE serving = TRUE
        ORDER BY user_id ASC";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 统一样式 -->
    <link rel="stylesheet" href="css/unified-style.css">
</head>
<body>
    <!-- 导航栏 -->
    <?php include_once 'common/navigation.php'; ?>

    <!-- 主要内容 -->
    <div class="container main-content">
        <!-- 页面标题 -->
        <div class="card">
            <div class="page-header">
                <h1 class="page-title">在职员工管理</h1>
                <p class="page-subtitle">管理在职员工的信息和状态</p>
            </div>
        </div>

        <!-- 消息提示 -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success fade-in">
                <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
            </div>
        <?php elseif (isset($error_message)): ?>
            <div class="alert alert-danger fade-in">
                <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <!-- 在职员工列表 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-users"></i> 在职员工列表</span>
                <div>
                    <button type="button" class="btn btn-success btn-sm me-2" onclick="updateAllRiskIndexes();">
                        <i class="fas fa-sync-alt"></i> 更新各在职员工风险指数
                    </button>
                    <button type="button" class="btn btn-warning btn-sm" onclick="document.getElementById('retireForm').submit();">
                        <i class="fas fa-user-times"></i> 标记为退休
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="post" id="retireForm">
                    <?php if ($result && $result->num_rows > 0): ?>
                        <div class="table-container">
                            <table class="table" id="servingTable">
                                <thead>
                                    <tr>
                                        <th style="width: 50px;">
                                            <input type="checkbox" id="select-all" onchange="toggleSelectAll(this)">
                                        </th>
                                        <th data-sort="user_id" data-type="number" class="sortable">
                                            <i class="fas fa-id-card"></i> 用户ID <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="name" data-type="text" class="sortable">
                                            <i class="fas fa-user"></i> 姓名 <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="gender" data-type="text" class="sortable">
                                            <i class="fas fa-venus-mars"></i> 性别 <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="position" data-type="text" class="sortable">
                                            <i class="fas fa-briefcase"></i> 职位 <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="online_status" data-type="number" class="sortable">
                                            <i class="fas fa-circle"></i> 在线状态 <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="dept_id" data-type="number" class="sortable">
                                            <i class="fas fa-building"></i> 部门归属 <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="latest_login" data-type="date" class="sortable">
                                            <i class="fas fa-clock"></i> 末次在线时间 <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="service_years" data-type="number" class="sortable">
                                            <i class="fas fa-calendar"></i> 入职年限 <span class="sort-indicator">⇅</span>
                                        </th>
                                        <th data-sort="risk_index" data-type="number" class="sortable">
                                            <i class="fas fa-exclamation-triangle"></i> 风险指数 <span class="sort-indicator">⇅</span>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($row = $result->fetch_assoc()): ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" name="user_ids[]" value="<?php echo $row['user_id']; ?>">
                                            </td>
                                            <td data-value="<?php echo $row['user_id']; ?>">
                                                <span class="text-dark"><?php echo htmlspecialchars($row['user_id']); ?></span>
                                            </td>
                                            <td data-value="<?php echo htmlspecialchars($row['name']); ?>">
                                                <strong><?php echo htmlspecialchars($row['name']); ?></strong>
                                            </td>
                                            <td data-value="<?php echo htmlspecialchars($row['gender']); ?>">
                                                <span class="text-dark">
                                                    <?php if ($row['gender'] === '男'): ?>
                                                        <i class="fas fa-mars text-primary"></i> 男
                                                    <?php elseif ($row['gender'] === '女'): ?>
                                                        <i class="fas fa-venus text-danger"></i> 女
                                                    <?php else: ?>
                                                        <i class="fas fa-question text-muted"></i> 未知
                                                    <?php endif; ?>
                                                </span>
                                            </td>
                                            <td data-value="<?php echo htmlspecialchars($row['position']); ?>">
                                                <?php echo htmlspecialchars($row['position']); ?>
                                            </td>
                                            <td data-value="<?php echo $row['online_status']; ?>">
                                                <?php
                                                // 判断在线状态 - 支持多种数据类型
                                                $isOnline = false;
                                                if ($row['online_status'] === 1 || $row['online_status'] === '1' ||
                                                    $row['online_status'] === true || $row['online_status'] === 'true' ||
                                                    $row['online_status'] === 'TRUE') {
                                                    $isOnline = true;
                                                }
                                                ?>
                                                <?php if ($isOnline): ?>
                                                    <span class="status-online">
                                                        <i class="fas fa-circle text-success"></i> 在线
                                                    </span>
                                                <?php else: ?>
                                                    <span class="status-offline">
                                                        <i class="fas fa-circle text-danger"></i> 离线
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td data-value="<?php echo $row['dept_id']; ?>">
                                                <span class="text-dark">
                                                    <?php
                                                    $dept_id = $row['dept_id'];
                                                    if (isset($deptMap[$dept_id])) {
                                                        echo '<small>' . htmlspecialchars($deptMap[$dept_id]) . '</small>';
                                                    } else {
                                                        echo '<small class="text-danger">未知部门</small>';
                                                    }
                                                    ?>
                                                    <span class="text-dark"> (ID: <?php echo htmlspecialchars($dept_id); ?>)</span>
                                                </span>
                                            </td>
                                            <td data-value="<?php echo $row['latest_login'] ? $row['latest_login'] : '1970-01-01 00:00:00'; ?>">
                                                <small class="text-muted">
                                                    <?php
                                                    if ($row['latest_login'] && $row['latest_login'] !== '0000-00-00 00:00:00') {
                                                        echo date('Y-m-d H:i', strtotime($row['latest_login']));
                                                    } else {
                                                        echo '从未登录';
                                                    }
                                                    ?>
                                                </small>
                                            </td>
                                            <td data-value="<?php echo $row['service_years']; ?>">
                                                <span class="text-dark fw-bold">
                                                    <?php echo htmlspecialchars($row['service_years']); ?> 年
                                                </span>
                                            </td>
                                            <td data-value="<?php echo $row['risk_index']; ?>">
                                                <?php
                                                $risk = number_format($row['risk_index'], 2);
                                                $risk_class = $risk > 3 ? 'text-danger' : ($risk > 1 ? 'text-warning' : 'text-success');
                                                ?>
                                                <span class="text-dark fw-bold">
                                                    <?php echo $risk; ?>
                                                </span>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php elseif ($result && $result->num_rows === 0): ?>
                        <div class="text-center py-5">
                            <div class="mb-3">
                                <i class="fas fa-users" style="font-size: 48px; color: #6c757d;"></i>
                            </div>
                            <h4 class="text-muted">暂无在职员工记录</h4>
                            <p class="text-muted">当前没有在职员工数据</p>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i> 无法获取员工数据，请检查数据库连接
                        </div>
                    <?php endif; ?>

                    <input type="hidden" name="retire" value="1">
                </form>
            </div>
        </div>

        <!-- 在职员工统计 -->
        <?php if ($result && $result->num_rows > 0): ?>
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-chart-pie"></i> 在职员工统计
                </div>
                <div class="card-body">
                    <?php
                    // 重新查询统计数据
                    $stats_sql = "SELECT
                                    COUNT(*) as total_serving,
                                    SUM(CASE WHEN gender = '男' THEN 1 ELSE 0 END) as male_count,
                                    SUM(CASE WHEN gender = '女' THEN 1 ELSE 0 END) as female_count,
                                    SUM(CASE WHEN online_status = 1 THEN 1 ELSE 0 END) as online_count,
                                    AVG(service_years) as avg_service_years,
                                    AVG(risk_index) as avg_risk_index
                                  FROM staff WHERE serving = TRUE";
                    $stats_result = $conn->query($stats_sql);
                    $stats = $stats_result->fetch_assoc();
                    ?>

                    <div class="info-grid">
                        <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-users text-primary"></i> 在职员工总数
                            </span>
                            <span class="info-value"><?php echo $stats['total_serving']; ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-mars text-info"></i> 男性员工
                            </span>
                            <span class="info-value"><?php echo $stats['male_count']; ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-venus text-danger"></i> 女性员工
                            </span>
                            <span class="info-value"><?php echo $stats['female_count']; ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-circle text-success"></i> 在线员工
                            </span>
                            <span class="info-value"><?php echo $stats['online_count']; ?></span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-calendar text-warning"></i> 平均工龄
                            </span>
                            <span class="info-value"><?php echo number_format($stats['avg_service_years'], 1); ?> 年</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-exclamation-triangle text-secondary"></i> 平均风险指数
                            </span>
                            <span class="info-value"><?php echo number_format($stats['avg_risk_index'], 2); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    // 全选/取消全选
    function toggleSelectAll(checkbox) {
        const checkboxes = document.querySelectorAll('input[name="user_ids[]"]');
        checkboxes.forEach(cb => cb.checked = checkbox.checked);
    }

    // 表单提交前验证
    document.getElementById('retireForm').addEventListener('submit', function(e) {
        const checkedBoxes = document.querySelectorAll('input[name="user_ids[]"]:checked');
        if (checkedBoxes.length === 0) {
            e.preventDefault();
            alert('请至少选择一名员工');
            return false;
        }

        const confirmMsg = `确定要将选中的 ${checkedBoxes.length} 名员工标记为退休状态吗？\n\n此操作可以撤销。`;
        if (!confirm(confirmMsg)) {
            e.preventDefault();
            return false;
        }
    });

    // 表格排序功能 - 支持三态排序
    class TableSorter {
        constructor(tableId) {
            this.table = document.getElementById(tableId);
            this.tbody = this.table.querySelector('tbody');
            this.headers = this.table.querySelectorAll('th.sortable');
            this.currentSort = { column: null, direction: null };
            this.originalOrder = Array.from(this.tbody.querySelectorAll('tr'));
            this.init();
        }

        init() {
            this.headers.forEach(header => {
                header.addEventListener('click', () => {
                    const column = header.dataset.sort;
                    const type = header.dataset.type || 'text';
                    this.sort(column, type, header);
                });
            });
        }

        sort(column, type, headerElement) {
            const rows = Array.from(this.tbody.querySelectorAll('tr'));

            // 三态排序：升序 -> 降序 -> 恢复默认（用户ID升序）
            let direction = 'asc';
            if (this.currentSort.column === column) {
                if (this.currentSort.direction === 'asc') {
                    direction = 'desc';
                } else if (this.currentSort.direction === 'desc') {
                    direction = 'default'; // 恢复默认排序
                } else {
                    direction = 'asc';
                }
            }

            // 更新当前排序状态
            this.currentSort = { column, direction };

            // 更新表头样式
            this.updateHeaderStyles(headerElement, direction);

            // 如果恢复默认排序，按用户ID升序
            if (direction === 'default') {
                this.restoreDefaultOrder();
                return;
            }

            // 排序行
            rows.sort((a, b) => {
                const aValue = this.getCellValue(a, column, type);
                const bValue = this.getCellValue(b, column, type);

                let result = this.compareValues(aValue, bValue, type);
                return direction === 'desc' ? -result : result;
            });

            // 重新插入排序后的行
            rows.forEach(row => this.tbody.appendChild(row));
        }

        getCellValue(row, column, type) {
            const columnIndex = Array.from(this.headers).findIndex(h => h.dataset.sort === column) + 1; // +1 for checkbox column
            const targetCell = row.cells[columnIndex];

            if (targetCell && targetCell.hasAttribute('data-value')) {
                let value = targetCell.getAttribute('data-value');

                // 类型转换
                switch (type) {
                    case 'number':
                        return parseFloat(value) || 0;
                    case 'date':
                        // 处理日期排序，将"从未登录"等空值设为最早时间
                        if (!value || value === '1970-01-01 00:00:00' || value === '0000-00-00 00:00:00') {
                            return 0; // 最早时间戳
                        }
                        return new Date(value).getTime() || 0;
                    default:
                        return value.toString().toLowerCase();
                }
            }

            return '';
        }

        compareValues(a, b, type) {
            if (type === 'number' || type === 'date') {
                return a - b;
            } else {
                return a.localeCompare(b, 'zh-CN');
            }
        }

        updateHeaderStyles(activeHeader, direction) {
            // 清除所有表头的排序样式
            this.headers.forEach(header => {
                header.classList.remove('sort-asc', 'sort-desc', 'sort-default');
            });

            // 添加当前排序样式
            if (direction === 'asc') {
                activeHeader.classList.add('sort-asc');
            } else if (direction === 'desc') {
                activeHeader.classList.add('sort-desc');
            } else if (direction === 'default') {
                activeHeader.classList.add('sort-default');
            }
        }

        restoreDefaultOrder() {
            // 恢复默认排序：按用户ID升序
            const rows = Array.from(this.tbody.querySelectorAll('tr'));
            rows.sort((a, b) => {
                const aUserId = parseFloat(this.getCellValue(a, 'user_id', 'number'));
                const bUserId = parseFloat(this.getCellValue(b, 'user_id', 'number'));
                return aUserId - bUserId;
            });

            // 重新插入排序后的行
            rows.forEach(row => this.tbody.appendChild(row));
        }
    }

    // 更新各在职员工风险指数函数
    function updateAllRiskIndexes() {
        if (!confirm('确定要更新所有在职员工的风险指数吗？\n\n此操作将根据violations表中的违反纪律积分重新计算所有员工的风险指数。')) {
            return;
        }

        // 显示加载状态
        const updateBtn = document.querySelector('button[onclick="updateAllRiskIndexes();"]');
        const originalContent = updateBtn.innerHTML;
        updateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 更新中...';
        updateBtn.disabled = true;

        // 发送AJAX请求
        fetch('serving_staff.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'update_risk_indexes=1'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                location.reload(); // 刷新页面显示最新风险指数
            } else {
                alert('更新失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('更新过程中发生错误，请稍后重试');
        })
        .finally(() => {
            // 恢复按钮状态
            updateBtn.innerHTML = originalContent;
            updateBtn.disabled = false;
        });
    }

    // 初始化表格排序
    document.addEventListener('DOMContentLoaded', function() {
        if (document.getElementById('servingTable')) {
            new TableSorter('servingTable');
        }

        // 表格行悬停效果
        const tableRows = document.querySelectorAll('.table tbody tr');

        tableRows.forEach(row => {
            row.addEventListener('mouseenter', function() {
                this.style.backgroundColor = 'rgba(13, 110, 253, 0.05)';
            });

            row.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '';
            });
        });
    });
    </script>

    <style>
    .sortable {
        cursor: pointer;
        user-select: none;
        position: relative;
        transition: background-color 0.2s;
    }

    .sortable:hover {
        background-color: rgba(22, 119, 255, 0.1);
    }

    .sort-indicator {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.6);
        margin-left: 5px;
    }

    .sortable.sort-asc .sort-indicator {
        color: var(--bs-primary);
    }

    .sortable.sort-desc .sort-indicator {
        color: var(--bs-primary);
    }

    .sortable.sort-default .sort-indicator {
        color: var(--bs-success);
    }

    .sortable.sort-asc .sort-indicator:after {
        content: ' ↑';
    }

    .sortable.sort-desc .sort-indicator:after {
        content: ' ↓';
    }

    .sortable.sort-default .sort-indicator:after {
        content: ' ⟲';
    }

    /* 在线状态样式 */
    .status-online {
        color: #198754 !important;
        font-weight: 500;
    }

    .status-offline {
        color: #dc3545 !important;
        font-weight: 500;
    }

    /* 确保文本颜色对比度 */
    .text-dark {
        color: #212529 !important;
    }
    </style>

    <?php
    // 关闭数据库连接
    if (isset($conn)) {
        $conn->close();
    }
    ?>
</body>
</html>